import { existsSync, readFileSync, writeFileSync } from "fs";
import { basename, dirname, join } from "path";
import { createDirSync, removeDir } from "../utils/FileUtil";
import { PublishLaya2Base } from "./PublishLaya2Base";

export class WebApkPublish extends PublishLaya2Base {
    get projDir() { return "apkgame" };
    get libJs() { return ""; }
    async createProject() {
        let toPath = this.mProjPath;
        if (existsSync(toPath)) {
            createDirSync(toPath);
            await this.doPack();
        } else {
            await this.copyDir(this.mTempProjPath, toPath);
            let projCfgPath = join(toPath, 'index.html');
            let fstr = readFileSync(projCfgPath).toString();
            fstr = fstr.replace(/\$\{APPID\}/g, this._publishVo.content.appId);
            fstr = fstr.replace('${PORJECT_NAME}', this.mProjectInfo.name);
            writeFileSync(projCfgPath, fstr);

            this.log('项目生成完毕 下一步可以开始打包游戏了');
            await this.doPack();
        }
    }


    async doPack() {
        await this.buildProject();
        // this.cpWebJs();
        await this.startZip();
        await this.startCpApk();
        this.packOver();
    }

    cpWebJs() {
        let htmlContent: string = readFileSync(join(this.mFromPath, "index.html")).toString();
        htmlContent = htmlContent.replace("index.js", "game.js");
        writeFileSync(join(this.mProjPath, "index.html"), htmlContent);
        let gameJsContent = `window.config = loadLib('./config.js');
        loadLib("./libs/nativeBridge.js");
        loadLib("./index.js");`
        writeFileSync(join(this.mProjPath, "game.js"), gameJsContent);
    }

    protected mWriteConfig() {
        writeFileSync(join(this.mProjPath, this.getConfigName()), "window.config = " + this.config + ";");
    }


    async startZip() {
        this.log("开始生成zip文件")
        const compressUtil = require("compressing");
        await compressUtil.zip.compressDir(this.mProjPath, join(this.mOutPath, `./${this._version}.zip`), { ignoreBase: true });
    }

    async startCpApk() {
        this.log("开始复制到安卓包");
        if (existsSync(this._publishVo.content.apkPath)) {
            await removeDir(this._publishVo.content.apkPath);
        }
        await this.copyDir(this.mProjPath, this._publishVo.content.apkPath);
    }


    saveFile(fileUrl: string, toPath: string, data: any) {
        let dirName = fileUrl;
        let fileName = basename(fileUrl);
        if (fileUrl.indexOf('/') >= 0) {
            dirName = dirname(fileUrl);
        }
        let destPath = join(toPath, dirName);
        createDirSync(destPath, () => {
            writeFileSync(join(destPath, fileName), data);
        });
    }
}